<template>
  <div class="follow-up-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>跟进记录管理</span>
          <el-button type="primary" @click="handleAdd">新增跟进</el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="客户姓名">
              <el-input v-model="searchForm.customerName" placeholder="请输入客户姓名" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="跟进方式">
              <el-select v-model="searchForm.followUpType" placeholder="请选择跟进方式" clearable style="width: 100%">
                <el-option label="电话" value="phone" />
                <el-option label="微信" value="wechat" />
                <el-option label="邮件" value="email" />
                <el-option label="面谈" value="meeting" />
                <el-option label="短信" value="sms" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="客户意向">
              <el-select v-model="searchForm.intention" placeholder="请选择客户意向" clearable style="width: 100%">
                <el-option label="无意向" value="no_intention" />
                <el-option label="意向一般" value="general" />
                <el-option label="意向较强" value="strong" />
                <el-option label="意向强烈" value="very_strong" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="跟进用户">
              <el-select v-model="searchForm.userId" placeholder="请选择跟进用户" clearable style="width: 100%">
                <el-option v-for="user in userOptions" :key="user.id" :label="user.name" :value="user.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="跟进时间">
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 批量操作 -->
      <!-- 在批量操作区域添加跟进方式配置按钮 -->
      <div class="batch-actions">
        <el-button 
          type="danger" 
          @click="handleBatchDelete"
          :disabled="selectedRows.length === 0"
          :loading="batchDeleteLoading"
        >
          批量删除
        </el-button>
        <el-button 
          @click="handleExport"
          :loading="exportLoading"
        >
          导出记录
        </el-button>
        <el-button 
          type="primary" 
          @click="handleConfigFollowUpTypes"
          icon="Setting"
        >
          跟进方式配置
        </el-button>
      </div>
      
      <!-- 添加跟进方式配置对话框 -->
      <el-dialog
        v-model="configDialog.visible"
        title="跟进方式配置"
        width="600px"
        class="responsive-dialog"
      >
        <div class="config-section">
          <div class="config-header">
            <span>跟进方式列表</span>
            <el-button type="primary" size="small" @click="handleAddFollowUpType" icon="Plus">
              新增方式
            </el-button>
          </div>
          
          <el-table :data="followUpTypeConfigs" border style="width: 100%">
            <el-table-column prop="name" label="方式名称" min-width="120" />
            <el-table-column prop="code" label="方式编码" min-width="100" />
            <el-table-column prop="description" label="描述" min-width="150" />
            <el-table-column prop="isActive" label="状态" width="80">
              <template #default="{ row }">
                <el-switch v-model="row.isActive" @change="handleToggleFollowUpType(row)" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button type="text" @click="handleEditFollowUpType(row)">编辑</el-button>
                <el-button type="text" @click="handleDeleteFollowUpType(row)" style="color: #f56c6c">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 新增/编辑跟进方式对话框 -->
        <el-dialog
          v-model="typeFormDialog.visible"
          :title="typeFormDialog.title"
          width="400px"
          append-to-body
        >
          <el-form :model="typeFormDialog.form" label-width="80px">
            <el-form-item label="方式名称">
              <el-input v-model="typeFormDialog.form.name" placeholder="请输入方式名称" />
            </el-form-item>
            <el-form-item label="方式编码">
              <el-input v-model="typeFormDialog.form.code" placeholder="请输入方式编码" />
            </el-form-item>
            <el-form-item label="描述">
              <el-input v-model="typeFormDialog.form.description" type="textarea" :rows="3" placeholder="请输入描述" />
            </el-form-item>
            <el-form-item label="图标">
              <el-select v-model="typeFormDialog.form.icon" placeholder="请选择图标">
                <el-option label="电话" value="Phone" />
                <el-option label="微信" value="ChatDotRound" />
                <el-option label="邮件" value="Message" />
                <el-option label="面谈" value="Avatar" />
                <el-option label="短信" value="ChatLineRound" />
              </el-select>
            </el-form-item>
            <el-form-item label="颜色">
              <el-color-picker v-model="typeFormDialog.form.color" />
            </el-form-item>
            <el-form-item label="排序">
              <el-input-number v-model="typeFormDialog.form.sort" :min="1" :max="99" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="typeFormDialog.visible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmitFollowUpType" :loading="typeSubmitLoading">确定</el-button>
          </template>
        </el-dialog>
        
        <template #footer>
          <el-button @click="configDialog.visible = false">关闭</el-button>
        </template>
      </el-dialog>
      
      <!-- 跟进记录表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :max-height="tableHeight"
        class="responsive-table"
      >
        <el-table-column type="selection" width="55" fixed="left" />
        <el-table-column prop="customerName" label="客户姓名" min-width="120" fixed="left" />
        <el-table-column prop="followUpType" label="跟进方式" width="100">
          <template #default="{ row }">
            <el-tag :type="getFollowUpTypeType(row.followUpType)">
              {{ getFollowUpTypeLabel(row.followUpType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="intention" label="客户意向" width="100">
          <template #default="{ row }">
            <el-tag :type="getIntentionType(row.intention)">
              {{ getIntentionLabel(row.intention) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="跟进内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="userName" label="跟进用户" width="120" />
        <el-table-column prop="followUpTime" label="跟进时间" width="160" />
        <el-table-column prop="nextFollowUpTime" label="下次跟进" width="160" />
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        <!-- 在表格操作列添加提醒设置按钮 -->
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleView(row)">查看</el-button>
            <el-button type="text" @click="handleEdit(row)">编辑</el-button>
            <el-button type="text" @click="handleSetReminder(row)" style="color: #e6a23c">提醒</el-button>
            <el-button type="text" @click="handleDelete(row)" style="color: #f56c6c">删除</el-button>
          </template>
        </el-table-column>
        
        <!-- 添加跟进提醒设置对话框 -->
        <el-dialog
          v-model="reminderDialog.visible"
          :title="reminderDialog.title"
          width="500px"
          class="responsive-dialog"
        >
          <el-form :model="reminderDialog.form" label-width="100px">
            <el-form-item label="客户名称">
              <el-input v-model="reminderDialog.form.customerName" disabled />
            </el-form-item>
            <el-form-item label="提醒时间">
              <el-date-picker
                v-model="reminderDialog.form.remindTime"
                type="datetime"
                placeholder="选择提醒时间"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="提醒方式">
              <el-radio-group v-model="reminderDialog.form.remindType">
                <el-radio label="system">系统提醒</el-radio>
                <el-radio label="email">邮件提醒</el-radio>
                <el-radio label="sms">短信提醒</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="提醒内容">
              <el-input
                v-model="reminderDialog.form.content"
                type="textarea"
                :rows="3"
                placeholder="请输入提醒内容"
              />
            </el-form-item>
            <el-form-item label="重复提醒">
              <el-switch v-model="reminderDialog.form.isRecurring" />
            </el-form-item>
            <el-form-item v-if="reminderDialog.form.isRecurring" label="重复周期">
              <el-input-number
                v-model="reminderDialog.form.recurringDays"
                :min="1"
                :max="30"
                :step="1"
                step-strictly
              />
              <span style="margin-left: 8px;">天</span>
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="reminderDialog.visible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmitReminder" :loading="reminderLoading">确定</el-button>
          </template>
        </el-dialog>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination responsive-pagination"
      />
    </el-card>

    <!-- 新增/编辑跟进记录对话框 -->
    <el-dialog
      v-model="formDialog.visible"
      :title="formDialog.title"
      width="600px"
      class="responsive-dialog"
    >
      <el-form ref="followUpFormRef" :model="formDialog.form" :rules="formRules" label-width="100px">
        <el-form-item label="客户" prop="customerId">
          <el-select
            v-model="formDialog.form.customerId"
            placeholder="请选择客户"
            filterable
            remote
            :remote-method="searchCustomers"
            :loading="customerLoading"
            style="width: 100%"
          >
            <el-option v-for="customer in customerOptions" :key="customer.id" :label="customer.name" :value="customer.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="跟进方式" prop="followUpType">
          <el-select v-model="formDialog.form.followUpType" placeholder="请选择跟进方式" style="width: 100%">
            <el-option label="电话" value="phone" />
            <el-option label="微信" value="wechat" />
            <el-option label="邮件" value="email" />
            <el-option label="面谈" value="meeting" />
            <el-option label="短信" value="sms" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户意向" prop="intention">
          <el-select v-model="formDialog.form.intention" placeholder="请选择客户意向" style="width: 100%">
            <el-option label="无意向" value="no_intention" />
            <el-option label="意向一般" value="general" />
            <el-option label="意向较强" value="strong" />
            <el-option label="意向强烈" value="very_strong" />
          </el-select>
        </el-form-item>
        <el-form-item label="跟进内容" prop="content">
          <el-input v-model="formDialog.form.content" type="textarea" :rows="4" placeholder="请输入跟进内容" />
        </el-form-item>
        <el-form-item label="下次跟进" prop="nextFollowUpTime">
          <el-date-picker
            v-model="formDialog.form.nextFollowUpTime"
            type="datetime"
            placeholder="选择下次跟进时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formDialog.form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="formDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 跟进记录详情对话框 -->
    <el-dialog
      v-model="detailDialog.visible"
      title="跟进记录详情"
      width="800px"
      class="responsive-dialog"
    >
      <!-- 基本信息 -->
      <el-card class="detail-section" shadow="never">
        <template #header>
          <div class="section-header">
            <el-icon><User /></el-icon>
            <span>基本信息</span>
          </div>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="客户姓名">
            <span class="customer-name">{{ detailDialog.data.customerName }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="联系方式">
            <el-icon><Phone /></el-icon>
            {{ detailDialog.data.customerPhone || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="跟进方式">
            <el-tag :type="getFollowUpTypeType(detailDialog.data.followUpType)" size="large">
              <el-icon style="margin-right: 4px;">
                <component :is="getFollowUpIcon(detailDialog.data.followUpType)" />
              </el-icon>
              {{ getFollowUpTypeLabel(detailDialog.data.followUpType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="客户意向">
            <el-tag 
              :type="getIntentionType(detailDialog.data.intention)" 
              size="large"
              effect="dark"
            >
              {{ getIntentionLabel(detailDialog.data.intention) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="跟进人员">
            <div class="user-info">
              <el-avatar :size="24" :style="{ backgroundColor: getUserAvatarColor(detailDialog.data.userId) }">
                {{ detailDialog.data.userName?.charAt(0) }}
              </el-avatar>
              <span style="margin-left: 8px;">{{ detailDialog.data.userName }}</span>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="跟进时间">
            <el-icon><Clock /></el-icon>
            {{ formatDateTime(detailDialog.data.followUpTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="下次跟进" :span="2">
            <el-icon><Calendar /></el-icon>
            <span :class="{ 'text-danger': isOverdue(detailDialog.data.nextFollowUpTime) }">
              {{ formatNextFollowUpTime(detailDialog.data.nextFollowUpTime) }}
            </span>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 跟进内容 -->
      <el-card class="detail-section" shadow="never" style="margin-top: 16px;">
        <template #header>
          <div class="section-header">
            <el-icon><Document /></el-icon>
            <span>跟进内容</span>
          </div>
        </template>
        <div class="follow-up-content">
          <div class="content-text">{{ detailDialog.data.content }}</div>
          <div v-if="detailDialog.data.attachments && detailDialog.data.attachments.length > 0" class="attachments">
            <div class="attachment-title">附件：</div>
            <div class="attachment-list">
              <div v-for="(file, index) in detailDialog.data.attachments" :key="index" class="attachment-item">
                <el-icon><Paperclip /></el-icon>
                <span class="file-name">{{ file.name }}</span>
                <el-button type="text" size="small" @click="downloadFile(file)">下载</el-button>
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 备注信息 -->
      <el-card class="detail-section" shadow="never" style="margin-top: 16px;" v-if="detailDialog.data.remark">
        <template #header>
          <div class="section-header">
            <el-icon><Edit /></el-icon>
            <span>备注信息</span>
          </div>
        </template>
        <div class="remark-content">{{ detailDialog.data.remark }}</div>
      </el-card>

      <!-- 客户跟进历史 -->
      <el-card class="detail-section" shadow="never" style="margin-top: 16px;">
        <template #header>
          <div class="section-header">
            <el-icon><Clock /></el-icon>
            <span>客户跟进历史</span>
            <el-tag type="info" size="small" style="margin-left: auto;">
              共 {{ detailDialog.followUpHistory?.length || 0 }} 条记录
            </el-tag>
          </div>
        </template>
        <div v-if="detailDialog.followUpHistory && detailDialog.followUpHistory.length > 0" class="follow-up-history">
          <el-timeline>
            <el-timeline-item 
              v-for="(record, index) in detailDialog.followUpHistory" 
              :key="record.id"
              :timestamp="formatDateTime(record.followUpTime)"
              :type="index === 0 ? 'primary' : 'info'"
              :color="index === 0 ? '#409EFF' : '#E4E7ED'"
              placement="top"
            >
              <el-card shadow="hover" :class="{ 'latest-record': index === 0 }">
                <div class="history-item-header">
                  <el-tag :type="getFollowUpTypeType(record.followUpType)" size="small">
                    {{ getFollowUpTypeLabel(record.followUpType) }}
                  </el-tag>
                  <el-tag 
                    :type="getIntentionType(record.intention)" 
                    size="small"
                    style="margin-left: 8px;"
                  >
                    {{ getIntentionLabel(record.intention) }}
                  </el-tag>
                  <span class="history-user">{{ record.userName }}</span>
                </div>
                <div class="history-content">{{ record.content }}</div>
                <div v-if="record.nextFollowUpTime" class="history-next-follow">
                  下次跟进：{{ formatDateTime(record.nextFollowUpTime) }}
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
        <el-empty v-else description="暂无跟进历史" />
      </el-card>

      <!-- 时间信息 -->
      <el-card class="detail-section" shadow="never" style="margin-top: 16px;">
        <template #header>
          <div class="section-header">
            <el-icon><InfoFilled /></el-icon>
            <span>时间信息</span>
          </div>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="创建时间">
            <el-icon><Clock /></el-icon>
            {{ formatDateTime(detailDialog.data.createdTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            <el-icon><Clock /></el-icon>
            {{ formatDateTime(detailDialog.data.updatedTime) }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialog.visible = false">关闭</el-button>
          <el-button type="primary" @click="handleEditFromDetail">编辑</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import {
  User,
  Phone,
  Clock,
  Calendar,
  Document,
  Edit,
  InfoFilled,
  Paperclip
} from '@element-plus/icons-vue'
import {
  getFollowUpList,
  createFollowUp,
  updateFollowUp,
  deleteFollowUp,
  exportFollowUps,
  searchCustomers,
  getCustomerFollowUpHistory,
  setFollowUpReminder,
  getFollowUpReminders,
  updateFollowUpReminderStatus,
  deleteFollowUpReminder
} from '@/api/crm'

// 表格数据
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])

// 搜索表单
const searchForm = reactive({
  customerName: '',
  followUpType: '',
  intention: '',
  userId: '',
  dateRange: []
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 下拉选项
const userOptions = ref([])
const customerOptions = ref([])

// 加载状态管理
const submitLoading = ref(false)
const batchDeleteLoading = ref(false)
const exportLoading = ref(false)
const customerLoading = ref(false)

// 表格高度计算
const tableHeight = computed(() => {
  const windowHeight = window.innerHeight
  return windowHeight - 350
})

// 表单引用
const followUpFormRef = ref<FormInstance>()

// 对话框状态
const detailDialog = reactive({
  visible: false,
  data: {}
})

const formDialog = reactive({
  visible: false,
  title: '新增跟进记录',
  form: {
    customerId: '',
    followUpType: '',
    intention: '',
    content: '',
    nextFollowUpTime: '',
    remark: ''
  }
})

// 表单验证规则
const formRules: FormRules = {
  customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
  followUpType: [{ required: true, message: '请选择跟进方式', trigger: 'change' }],
  intention: [{ required: true, message: '请选择客户意向', trigger: 'change' }],
  content: [
    { required: true, message: '请输入跟进内容', trigger: 'blur' },
    { min: 5, max: 1000, message: '跟进内容长度为5-1000个字符', trigger: 'blur' }
  ],
  remark: [{ max: 500, message: '备注长度不能超过500个字符', trigger: 'blur' }]
}

// 获取跟进方式标签
const getFollowUpTypeLabel = (type: string) => {
  const labels: Record<string, string> = {
    phone: '电话',
    wechat: '微信',
    email: '邮件',
    meeting: '面谈',
    sms: '短信'
  }
  return labels[type] || type
}

// 获取跟进方式类型
const getFollowUpTypeType = (type: string) => {
  const types: Record<string, string> = {
    phone: 'primary',
    wechat: 'success',
    email: 'warning',
    meeting: 'danger',
    sms: 'info'
  }
  return types[type] || 'info'
}

// 获取客户意向标签
const getIntentionLabel = (intention: string) => {
  const labels: Record<string, string> = {
    no_intention: '无意向',
    general: '意向一般',
    strong: '意向较强',
    very_strong: '意向强烈'
  }
  return labels[intention] || intention
}

// 获取客户意向类型
const getIntentionType = (intention: string) => {
  const types: Record<string, string> = {
    no_intention: 'danger',
    general: 'warning',
    strong: 'primary',
    very_strong: 'success'
  }
  return types[intention] || 'info'
}

// 获取跟进记录列表
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const res = await getFollowUpList(params)
    tableData.value = res.rows
    pagination.total = res.total
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '获取跟进记录列表失败'
    ElMessage.error(errorMessage)
    console.error('获取跟进记录列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取下拉选项
const fetchOptions = async () => {
  try {
    // 获取用户列表
    const res = await getFollowUpList({ pageSize: 100 })
    const uniqueUsers = Array.from(new Set(res.rows.map((item: any) => item.userId)))
      .map(userId => {
        const user = res.rows.find((item: any) => item.userId === userId)
        return { id: userId, name: user.userName }
      })
    userOptions.value = uniqueUsers
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '获取选项数据失败'
    ElMessage.error(errorMessage)
    console.error('获取选项数据失败:', error)
  }
}

// 搜索客户
const searchCustomers = async (keyword: string) => {
  if (!keyword) return
  customerLoading.value = true
  try {
    const res = await searchCustomers({ keyword })
    customerOptions.value = res
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '搜索客户失败'
    ElMessage.error(errorMessage)
    console.error('搜索客户失败:', error)
  } finally {
    customerLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    customerName: '',
    followUpType: '',
    intention: '',
    userId: '',
    dateRange: []
  })
  handleSearch()
}

// 分页
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  fetchData()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  fetchData()
}

// 选择行
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
}

// 获取跟进方式图标
const getFollowUpIcon = (type: string) => {
  const icons = {
    phone: Phone,
    wechat: 'ChatDotRound',
    email: 'Message',
    meeting: 'Avatar',
    sms: 'ChatLineRound'
  }
  return icons[type] || Document
}

// 获取用户头像颜色
const getUserAvatarColor = (userId: string) => {
  const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']
  const hash = userId.split('').reduce((a, b) => {
    a = ((a << 5) - a) + b.charCodeAt(0)
    return a & a
  }, 0)
  return colors[Math.abs(hash) % colors.length]
}

// 格式化日期时间
const formatDateTime = (datetime: string) => {
  if (!datetime) return '-'
  return new Date(datetime).toLocaleString('zh-CN')
}

// 格式化下次跟进时间
const formatNextFollowUpTime = (datetime: string) => {
  if (!datetime) return '暂无安排'
  return formatDateTime(datetime)
}

// 检查是否逾期
const isOverdue = (datetime: string) => {
  if (!datetime) return false
  return new Date(datetime) < new Date()
}

// 下载文件
const downloadFile = (file: any) => {
  // 实现文件下载逻辑
  console.log('下载文件:', file)
}

// 从详情页面编辑
const handleEditFromDetail = () => {
  detailDialog.visible = false
  handleEdit(detailDialog.data)
}

// 对话框状态
const detailDialog = reactive({
  visible: false,
  data: {},
  followUpHistory: []
})

// 查看详情
const handleView = async (row: any) => {
  try {
    const res = await getFollowUpList({ id: row.id })
    detailDialog.data = res.rows[0]
    
    // 获取客户跟进历史
    if (detailDialog.data.customerId) {
      const historyRes = await getCustomerFollowUpHistory(detailDialog.data.customerId)
      detailDialog.followUpHistory = historyRes.rows || []
    }
    
    detailDialog.visible = true
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '获取跟进记录详情失败'
    ElMessage.error(errorMessage)
    console.error('获取跟进记录详情失败:', error)
  }
}

// 新增
const handleAdd = () => {
  formDialog.title = '新增跟进记录'
  formDialog.form = {
    customerId: '',
    followUpType: '',
    intention: '',
    content: '',
    nextFollowUpTime: '',
    remark: ''
  }
  formDialog.visible = true
}

// 编辑
const handleEdit = async (row: any) => {
  try {
    const res = await getFollowUpList({ id: row.id })
    formDialog.title = '编辑跟进记录'
    formDialog.form = { ...res.rows[0] }
    formDialog.visible = true
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '获取跟进记录详情失败'
    ElMessage.error(errorMessage)
    console.error('获取跟进记录详情失败:', error)
  }
}

// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该跟进记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteFollowUp(row.id)
    ElMessage.success('删除跟进记录成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) return
  
  batchDeleteLoading.value = true
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条跟进记录吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const ids = selectedRows.value.map(row => row.id)
    await Promise.all(ids.map(id => deleteFollowUp(id)))
    ElMessage.success('批量删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  } finally {
    batchDeleteLoading.value = false
  }
}

// 导出
const handleExport = async () => {
  exportLoading.value = true
  try {
    const blob = await exportFollowUps(searchForm)
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `跟进记录_${new Date().toLocaleDateString()}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '导出失败'
    ElMessage.error(errorMessage)
    console.error('导出失败:', error)
  } finally {
    exportLoading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!followUpFormRef.value) return
  
  await followUpFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (formDialog.title === '新增跟进记录') {
          await createFollowUp(formDialog.form)
          ElMessage.success('新增跟进记录成功')
        } else {
          await updateFollowUp(formDialog.form.id, formDialog.form)
          ElMessage.success('更新跟进记录成功')
        }
        formDialog.visible = false
        fetchData()
      } catch (error: any) {
        const errorMessage = error?.response?.data?.message || error?.message || '操作失败'
        ElMessage.error(errorMessage)
        console.error('提交表单失败:', error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 初始化
onMounted(() => {
  fetchData()
  fetchOptions()
  fetchUpcomingReminders()
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    // 表格高度会自动重新计算
  })
  
  // 定时检查即将到期的跟进（每30分钟检查一次）
  setInterval(() => {
    checkUpcomingFollowUps()
  }, 30 * 60 * 1000)
})

// 添加跟进提醒相关的状态变量
const reminderDialog = reactive({
  visible: false,
  title: '跟进提醒设置',
  form: {
    customerId: '',
    customerName: '',
    remindTime: '',
    remindType: 'system',
    content: '',
    isRecurring: false,
    recurringDays: 7
  }
})

const upcomingReminders = ref([])
const reminderLoading = ref(false)

// 获取即将到期的跟进提醒
const fetchUpcomingReminders = async () => {
  reminderLoading.value = true
  try {
     // 获取未来7天内需要跟进的记录
    const res = await getFollowUpList({
      pageSize: 100,
      nextFollowUpStart: new Date().toISOString(),
      nextFollowUpEnd: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString()
    })
    upcomingReminders.value = res.rows.filter(item => 
      item.nextFollowUpTime && new Date(item.nextFollowUpTime) > new Date()
    )
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '获取跟进提醒失败'
    ElMessage.error(errorMessage)
    console.error('获取跟进提醒失败:', error)
  } finally {
    reminderLoading.value = false
  }
}

// 获取意向等级配置
const getIntentionLevelConfigs = () => {
  return [
    {
      id: 1,
      name: 'A级',
      code: 'A',
      description: '意向强烈，成交概率高',
      color: '#F56C6C',
      sort: 1,
      isActive: true
    },
    {
      id: 2,
      name: 'B级',
      code: 'B',
      description: '意向较强，有成交可能',
      color: '#E6A23C',
      sort: 2,
      isActive: true
    },
    {
      id: 3,
      name: 'C级',
      code: 'C',
      description: '意向一般，需要持续跟进',
      color: '#409EFF',
      sort: 3,
      isActive: true
    },
    {
      id: 4,
      name: 'D级',
      code: 'D',
      description: '意向较弱，成交概率低',
      color: '#67C23A',
      sort: 4,
      isActive: true
    }
  ]
}

// 设置跟进提醒
const handleSetReminder = (row: any) => {
  reminderDialog.form = {
    customerId: row.customerId,
    customerName: row.customerName,
    remindTime: row.nextFollowUpTime || '',
    remindType: 'system',
    content: `跟进客户：${row.customerName}`,
    isRecurring: false,
    recurringDays: 7
  }
  reminderDialog.visible = true
}

// 提交提醒设置
const handleSubmitReminder = async () => {
  try {
     // 这里调用设置提醒的API
    await setFollowUpReminder(reminderDialog.form)
    ElMessage.success('提醒设置成功')
    reminderDialog.visible = false
    fetchUpcomingReminders()
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '提醒设置失败'
    ElMessage.error(errorMessage)
    console.error('提醒设置失败:', error)
  }
}

// 检查是否有即将到期的跟进
const checkUpcomingFollowUps = () => {
  const now = new Date()
  const upcoming = upcomingReminders.value.filter(item => {
    const followUpTime = new Date(item.nextFollowUpTime)
    const timeDiff = followUpTime.getTime() - now.getTime()
    return timeDiff > 0 && timeDiff <= 24 * 60 * 60 * 1000 // 24小时内
  })
  
  if (upcoming.length > 0) {
     // 显示提醒通知
    upcoming.forEach(item => {
      ElMessage.warning({
        message: `客户 ${item.customerName} 的跟进时间即将到期！`,
        duration: 0,
        showClose: true
      })
    })
  }
}
// 添加跟进方式配置相关的状态变量
const configDialog = reactive({
  visible: false
})

const typeFormDialog = reactive({
  visible: false,
  title: '新增跟进方式',
  form: {
    name: '',
    code: '',
    description: '',
    icon: 'Phone',
    color: '#409EFF',
    sort: 1
  }
})

const typeSubmitLoading = ref(false)
const followUpTypeConfigs = ref([
  {
    id: 1,
    name: '电话',
    code: 'phone',
    description: '通过电话联系客户',
    icon: 'Phone',
    color: '#409EFF',
    sort: 1,
    isActive: true
  },
  {
    id: 2,
    name: '微信',
    code: 'wechat',
    description: '通过微信联系客户',
    icon: 'ChatDotRound',
    color: '#67C23A',
    sort: 2,
    isActive: true
  },
  {
    id: 3,
    name: '邮件',
    code: 'email',
    description: '通过邮件联系客户',
    icon: 'Message',
    color: '#E6A23C',
    sort: 3,
    isActive: true
  },
  {
    id: 4,
    name: '面谈',
    code: 'meeting',
    description: '面对面沟通',
    icon: 'Avatar',
    color: '#F56C6C',
    sort: 4,
    isActive: true
  },
  {
    id: 5,
    name: '短信',
    code: 'sms',
    description: '通过短信联系客户',
    icon: 'ChatLineRound',
    color: '#909399',
    sort: 5,
    isActive: true
  }
])

// 跟进方式配置相关的方法
const handleConfigFollowUpTypes = () => {
  configDialog.visible = true
}

const handleAddFollowUpType = () => {
  typeFormDialog.title = '新增跟进方式'
  typeFormDialog.form = {
    name: '',
    code: '',
    description: '',
    icon: 'Phone',
    color: '#409EFF',
    sort: followUpTypeConfigs.value.length + 1
  }
  typeFormDialog.visible = true
}

const handleEditFollowUpType = (row: any) => {
  typeFormDialog.title = '编辑跟进方式'
  typeFormDialog.form = { ...row }
  typeFormDialog.visible = true
}

const handleDeleteFollowUpType = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除跟进方式"${row.name}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = followUpTypeConfigs.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      followUpTypeConfigs.value.splice(index, 1)
    }
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleToggleFollowUpType = (row: any) => {
  const message = row.isActive ? '启用' : '禁用'
  ElMessage.success(`${message}跟进方式"${row.name}"成功`)
}

const handleSubmitFollowUpType = async () => {
  if (!typeFormDialog.form.name || !typeFormDialog.form.code) {
    ElMessage.error('请填写完整信息')
    return
  }
  
  typeSubmitLoading.value = true
  try {
    if (typeFormDialog.title === '新增跟进方式') {
      const newType = {
        ...typeFormDialog.form,
        id: Date.now(),
        isActive: true
      }
      followUpTypeConfigs.value.push(newType)
      ElMessage.success('新增跟进方式成功')
    } else {
      const index = followUpTypeConfigs.value.findIndex(item => item.id === typeFormDialog.form.id)
      if (index > -1) {
        followUpTypeConfigs.value[index] = { ...typeFormDialog.form }
      }
      ElMessage.success('编辑跟进方式成功')
    }
    typeFormDialog.visible = false
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    typeSubmitLoading.value = false
  }
}
</script>

<template>
  <div class="follow-up-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>跟进记录管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAdd">新增跟进</el-button>
            <el-button @click="handleBatchDelete" :disabled="selectedRows.length === 0" :loading="batchDeleteLoading">
              批量删除
            </el-button>
            <el-button @click="handleExport" :loading="exportLoading">导出</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" label-width="80px" class="search-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="客户姓名">
              <el-input v-model="searchForm.customerName" placeholder="请输入客户姓名" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="跟进方式">
              <el-select v-model="searchForm.followUpType" placeholder="请选择跟进方式" clearable>
                <el-option label="电话" value="phone" />
                <el-option label="微信" value="wechat" />
                <el-option label="邮件" value="email" />
                <el-option label="面谈" value="meeting" />
                <el-option label="短信" value="sms" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户意向">
              <el-select v-model="searchForm.intention" placeholder="请选择客户意向" clearable>
                <el-option label="无意向" value="no_intention" />
                <el-option label="意向一般" value="general" />
                <el-option label="意向较强" value="strong" />
                <el-option label="意向强烈" value="very_strong" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="跟进人">
              <el-select v-model="searchForm.userId" placeholder="请选择跟进人" clearable>
                <el-option
                  v-for="user in userOptions"
                  :key="user.id"
                  :label="user.name"
                  :value="user.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="跟进时间">
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        :height="tableHeight"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="customerName" label="客户姓名" min-width="120" />
        <el-table-column prop="phone" label="手机号码" width="120" />
        <el-table-column prop="followUpTime" label="跟进时间" width="160" />
        <el-table-column prop="followUpMethod" label="跟进方式" width="100">
          <template #default="{ row }">
            <el-tag size="small" :type="getFollowUpTypeType(row.followUpMethod)">
              {{ getFollowUpTypeLabel(row.followUpMethod) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="customerIntention" label="客户意向" width="100">
          <template #default="{ row }">
            <el-tag size="small" :type="getIntentionType(row.customerIntention)">
              {{ getIntentionLabel(row.customerIntention) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="followUpContent" label="跟进内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="nextFollowUpTime" label="下次跟进时间" width="160" />
        <el-table-column prop="followUpUserName" label="跟进人" width="100" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleView(row)">查看</el-button>
            <el-button type="text" @click="handleEdit(row)">编辑</el-button>
            <el-button type="text" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </el-card>

    <!-- 表单对话框 -->
    <el-dialog
      v-model="formDialog.visible"
      :title="formDialog.title"
      width="600px"
    >
      <el-form
        ref="followUpFormRef"
        :model="formDialog.form"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="客户" prop="customerId">
          <el-select
            v-model="formDialog.form.customerId"
            placeholder="请选择客户"
            filterable
            remote
            :remote-method="searchCustomers"
            :loading="customerLoading"
            @change="handleCustomerChange"
          >
            <el-option
              v-for="customer in customerOptions"
              :key="customer.id"
              :label="customer.customerName"
              :value="customer.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="跟进方式" prop="followUpType">
          <el-select v-model="formDialog.form.followUpType" placeholder="请选择跟进方式">
            <el-option
              v-for="type in followUpTypeConfigs"
              :key="type.code"
              :label="type.name"
              :value="type.code"
              :disabled="!type.isActive"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户意向" prop="intention">
          <el-select v-model="formDialog.form.intention" placeholder="请选择客户意向">
            <el-option label="无意向" value="no_intention" />
            <el-option label="意向一般" value="general" />
            <el-option label="意向较强" value="strong" />
            <el-option label="意向强烈" value="very_strong" />
          </el-select>
        </el-form-item>
        <el-form-item label="跟进内容" prop="content">
          <el-input
            v-model="formDialog.form.content"
            type="textarea"
            :rows="4"
            placeholder="请输入跟进内容"
          />
        </el-form-item>
        <el-form-item label="下次跟进时间">
          <el-date-picker
            v-model="formDialog.form.nextFollowUpTime"
            type="datetime"
            placeholder="请选择下次跟进时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formDialog.form.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="formDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialog.visible"
      title="跟进记录详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="客户姓名">{{ detailDialog.data.customerName }}</el-descriptions-item>
        <el-descriptions-item label="手机号码">{{ detailDialog.data.phone }}</el-descriptions-item>
        <el-descriptions-item label="跟进时间">{{ detailDialog.data.followUpTime }}</el-descriptions-item>
        <el-descriptions-item label="跟进方式">
          <el-tag size="small" :type="getFollowUpTypeType(detailDialog.data.followUpMethod)">
            {{ getFollowUpTypeLabel(detailDialog.data.followUpMethod) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="客户意向">
          <el-tag size="small" :type="getIntentionType(detailDialog.data.customerIntention)">
            {{ getIntentionLabel(detailDialog.data.customerIntention) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="下次跟进时间">{{ detailDialog.data.nextFollowUpTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="跟进人">{{ detailDialog.data.followUpUserName }}</el-descriptions-item>
        <el-descriptions-item label="跟进内容" :span="2">{{ detailDialog.data.followUpContent }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailDialog.data.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
        <el-button type="primary" @click="handleEditFromDetail">编辑</el-button>
      </template>
    </el-dialog>
  </div>
</template>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import {
  User,
  Phone,
  Clock,
  Calendar,
  Document,
  Edit,
  InfoFilled,
  Paperclip
} from '@element-plus/icons-vue'
import {
  getFollowUpList,
  createFollowUp,
  updateFollowUp,
  deleteFollowUp,
  exportFollowUps,
  searchCustomers,
  getCustomerFollowUpHistory
} from '@/api/crm'

// 表格数据
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])

// 搜索表单
const searchForm = reactive({
  customerName: '',
  followUpType: '',
  intention: '',
  userId: '',
  dateRange: []
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 下拉选项
const userOptions = ref([])
const customerOptions = ref([])

// 加载状态管理
const submitLoading = ref(false)
const batchDeleteLoading = ref(false)
const exportLoading = ref(false)
const customerLoading = ref(false)

// 表格高度计算
const tableHeight = computed(() => {
  const windowHeight = window.innerHeight
  return windowHeight - 350
})

// 表单引用
const followUpFormRef = ref<FormInstance>()

// 对话框状态
const detailDialog = reactive({
  visible: false,
  data: {}
})

const formDialog = reactive({
  visible: false,
  title: '新增跟进记录',
  form: {
    customerId: '',
    followUpType: '',
    intention: '',
    content: '',
    nextFollowUpTime: '',
    remark: ''
  }
})

// 表单验证规则
const formRules: FormRules = {
  customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
  followUpType: [{ required: true, message: '请选择跟进方式', trigger: 'change' }],
  intention: [{ required: true, message: '请选择客户意向', trigger: 'change' }],
  content: [{ required: true, message: '请输入跟进内容', trigger: 'blur' }]
}

// 获取跟进方式标签
const getFollowUpTypeLabel = (type: string) => {
  const labels: Record<string, string> = {
    phone: '电话',
    wechat: '微信',
    email: '邮件',
    meeting: '面谈',
    sms: '短信'
  }
  return labels[type] || type
}

// 获取跟进方式类型
const getFollowUpTypeType = (type: string) => {
  const types: Record<string, string> = {
    phone: 'primary',
    wechat: 'success',
    email: 'warning',
    meeting: 'danger',
    sms: 'info'
  }
  return types[type] || 'info'
}

// 获取客户意向标签
const getIntentionLabel = (intention: string) => {
  const labels: Record<string, string> = {
    no_intention: '无意向',
    general: '意向一般',
    strong: '意向较强',
    very_strong: '意向强烈'
  }
  return labels[intention] || intention
}

// 获取客户意向类型
const getIntentionType = (intention: string) => {
  const types: Record<string, string> = {
    no_intention: 'danger',
    general: 'warning',
    strong: 'primary',
    very_strong: 'success'
  }
  return types[intention] || 'info'
}

// 获取跟进记录列表
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const res = await getFollowUpList(params)
    tableData.value = res.rows
    pagination.total = res.total
  } catch (error) {
    ElMessage.error('获取跟进记录列表失败')
  } finally {
    loading.value = false
  }
}

// 获取下拉选项
const fetchOptions = async () => {
  try {
    // 获取用户列表
    const res = await getFollowUpList({ pageSize: 100 })
    const uniqueUsers = Array.from(new Set(res.rows.map((item: any) => item.userId)))
      .map(userId => {
        const user = res.rows.find((item: any) => item.userId === userId)
        return { id: userId, name: user.userName }
      })
    userOptions.value = uniqueUsers
  } catch (error) {
    ElMessage.error('获取选项数据失败')
  }
}

// 搜索客户
const searchCustomers = async (keyword: string) => {
  if (!keyword) return
  customerLoading.value = true
  try {
    const res = await searchCustomers({ keyword })
    customerOptions.value = res
  } catch (error) {
    ElMessage.error('搜索客户失败')
  } finally {
    customerLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    customerName: '',
    followUpType: '',
    intention: '',
    userId: '',
    dateRange: []
  })
  handleSearch()
}

// 分页
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  fetchData()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  fetchData()
}

// 选择行
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
}

// 获取跟进方式图标
const getFollowUpIcon = (type: string) => {
  const icons = {
    phone: Phone,
    wechat: 'ChatDotRound',
    email: 'Message',
    meeting: 'Avatar',
    sms: 'ChatLineRound'
  }
  return icons[type] || Document
}

// 获取用户头像颜色
const getUserAvatarColor = (userId: string) => {
  const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']
  const hash = userId.split('').reduce((a, b) => {
    a = ((a << 5) - a) + b.charCodeAt(0)
    return a & a
  }, 0)
  return colors[Math.abs(hash) % colors.length]
}

// 格式化日期时间
const formatDateTime = (datetime: string) => {
  if (!datetime) return '-'
  return new Date(datetime).toLocaleString('zh-CN')
}

// 格式化下次跟进时间
const formatNextFollowUpTime = (datetime: string) => {
  if (!datetime) return '暂无安排'
  return formatDateTime(datetime)
}

// 检查是否逾期
const isOverdue = (datetime: string) => {
  if (!datetime) return false
  return new Date(datetime) < new Date()
}

// 下载文件
const downloadFile = (file: any) => {
  // 实现文件下载逻辑
  console.log('下载文件:', file)
}

// 从详情页面编辑
const handleEditFromDetail = () => {
  detailDialog.visible = false
  handleEdit(detailDialog.data)
}

// 对话框状态
const detailDialog = reactive({
  visible: false,
  data: {},
  followUpHistory: []
})

// 查看详情
const handleView = async (row: any) => {
  try {
    const res = await getFollowUpList({ id: row.id })
    detailDialog.data = res.rows[0]
    
    // 获取客户跟进历史
    if (detailDialog.data.customerId) {
      const historyRes = await getCustomerFollowUpHistory(detailDialog.data.customerId)
      detailDialog.followUpHistory = historyRes.rows || []
    }
    
    detailDialog.visible = true
  } catch (error) {
    ElMessage.error('获取跟进记录详情失败')
  }
}

// 新增
const handleAdd = () => {
  formDialog.title = '新增跟进记录'
  formDialog.form = {
    customerId: '',
    followUpType: '',
    intention: '',
    content: '',
    nextFollowUpTime: '',
    remark: ''
  }
  formDialog.visible = true
}

// 编辑
const handleEdit = async (row: any) => {
  try {
    const res = await getFollowUpList({ id: row.id })
    formDialog.title = '编辑跟进记录'
    formDialog.form = { ...res.rows[0] }
    formDialog.visible = true
  } catch (error) {
    ElMessage.error('获取跟进记录详情失败')
  }
}

// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该跟进记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteFollowUp(row.id)
    ElMessage.success('删除跟进记录成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) return
  
  batchDeleteLoading.value = true
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条跟进记录吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const ids = selectedRows.value.map(row => row.id)
    await Promise.all(ids.map(id => deleteFollowUp(id)))
    ElMessage.success('批量删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  } finally {
    batchDeleteLoading.value = false
  }
}

// 导出
const handleExport = async () => {
  exportLoading.value = true
  try {
    const blob = await exportFollowUps(searchForm)
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `跟进记录_${new Date().toLocaleDateString()}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  } finally {
    exportLoading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!followUpFormRef.value) return
  
  await followUpFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (formDialog.title === '新增跟进记录') {
          await createFollowUp(formDialog.form)
          ElMessage.success('新增跟进记录成功')
        } else {
          await updateFollowUp(formDialog.form.id, formDialog.form)
          ElMessage.success('更新跟进记录成功')
        }
        formDialog.visible = false
        fetchData()
      } catch (error) {
        ElMessage.error('操作失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 初始化
onMounted(() => {
  fetchData()
  fetchOptions()
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    // 表格高度会自动重新计算
  })
})

// 添加跟进提醒相关的状态变量
const reminderDialog = reactive({
  visible: false,
  title: '跟进提醒设置',
  form: {
    customerId: '',
    customerName: '',
    remindTime: '',
    remindType: 'system',
    content: '',
    isRecurring: false,
    recurringDays: 7
  }
})

const upcomingReminders = ref([])
const reminderLoading = ref(false)

// 获取即将到期的跟进提醒
const fetchUpcomingReminders = async () => {
  reminderLoading.value = true
  try {
     // 获取未来7天内需要跟进的记录
    const res = await getFollowUpList({
      pageSize: 100,
      nextFollowUpStart: new Date().toISOString(),
      nextFollowUpEnd: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString()
    })
    upcomingReminders.value = res.rows.filter(item => 
      item.nextFollowUpTime && new Date(item.nextFollowUpTime) > new Date()
    )
  } catch (error) {
    ElMessage.error('获取跟进提醒失败')
  } finally {
    reminderLoading.value = false
  }
}

// 设置跟进提醒
const handleSetReminder = (row: any) => {
  reminderDialog.form = {
    customerId: row.customerId,
    customerName: row.customerName,
    remindTime: row.nextFollowUpTime || '',
    remindType: 'system',
    content: `跟进客户：${row.customerName}`,
    isRecurring: false,
    recurringDays: 7
  }
  reminderDialog.visible = true
}

// 提交提醒设置
const handleSubmitReminder = async () => {
  try {
     // 这里调用设置提醒的API
    await setFollowUpReminder(reminderDialog.form)
    ElMessage.success('提醒设置成功')
    reminderDialog.visible = false
    fetchUpcomingReminders()
  } catch (error) {
    ElMessage.error('提醒设置失败')
  }
}

// 检查是否有即将到期的跟进
const checkUpcomingFollowUps = () => {
  const now = new Date()
  const upcoming = upcomingReminders.value.filter(item => {
    const followUpTime = new Date(item.nextFollowUpTime)
    const timeDiff = followUpTime.getTime() - now.getTime()
    return timeDiff > 0 && timeDiff <= 24 * 60 * 60 * 1000 // 24小时内
  })
  
  if (upcoming.length > 0) {
     // 显示提醒通知
    upcoming.forEach(item => {
      ElMessage.warning({
        message: `客户 ${item.customerName} 的跟进时间即将到期！`,
        duration: 0,
        showClose: true
      })
    })
  }
}
</script>

<style scoped lang="scss">
.follow-up-management {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
  }

  .search-form {
    margin-bottom: 20px;
  }

  .batch-actions {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  // 响应式设计
  @media screen and (max-width: 768px) {
    .card-header {
      flex-direction: column;
      align-items: flex-start;
    }

    .batch-actions {
      justify-content: center;
    }

    .pagination {
      justify-content: center;
    }
  }

  @media screen and (max-width: 480px) {
    .search-form {
      .el-form-item {
        margin-bottom: 10px;
      }
    }

    .batch-actions {
      .el-button {
        margin-bottom: 5px;
      }
    }
  }
}

// 全局响应式样式
.responsive-table {
  :deep(.el-table__header) {
    th {
      background-color: #f5f7fa;
      font-weight: 600;
    }
  }
}

.responsive-pagination {
  :deep(.el-pagination__sizes) {
    @media screen and (max-width: 768px) {
      display: none;
    }
  }
}

.responsive-dialog {
  @media screen and (max-width: 768px) {
    :deep(.el-dialog) {
      width: 95% !important;
      margin-top: 10vh !important;
    }
  }
}

// 详情对话框样式
.detail-section {
  :deep(.el-card__header) {
    padding: 12px 16px;
    background-color: #f5f7fa;
    border-bottom: 1px solid #e4e7ed;
  }
  
  :deep(.el-card__body) {
    padding: 16px;
  }
}

.section-header {
  display: flex;
  align-items: center;
  font-weight: 600;
  color: #303133;
  
  .el-icon {
    margin-right: 8px;
    font-size: 16px;
  }
}

.customer-name {
  font-weight: 600;
  color: #409EFF;
  font-size: 14px;
}

.user-info {
  display: flex;
  align-items: center;
}

.follow-up-content {
  .content-text {
    font-size: 14px;
    line-height: 1.6;
    color: #303133;
    margin-bottom: 16px;
  }
  
  .attachments {
    .attachment-title {
      font-size: 12px;
      color: #909399;
      margin-bottom: 8px;
    }
    
    .attachment-list {
      display: flex;
      flex-direction: column;
      gap: 8px;
    }
    
    .attachment-item {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 8px;
      background-color: #f5f7fa;
      border-radius: 4px;
      
      .file-name {
        flex: 1;
        font-size: 12px;
        color: #606266;
      }
    }
  }
}

.remark-content {
  font-size: 14px;
  line-height: 1.6;
  color: #606266;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border-left: 4px solid #409EFF;
}

.follow-up-history {
  :deep(.el-timeline) {
    padding-left: 0;
  }
  
  :deep(.el-timeline-item__wrapper) {
    padding-left: 28px;
  }
  
  .latest-record {
    border: 1px solid #409EFF;
    background-color: #ecf5ff;
  }
  
  .history-item-header {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    
    .history-user {
      margin-left: auto;
      font-size: 12px;
      color: #909399;
    }
  }
  
  .history-content {
    font-size: 14px;
    line-height: 1.5;
    color: #303133;
    margin-bottom: 8px;
  }
  
  .history-next-follow {
    font-size: 12px;
    color: #909399;
    margin-top: 8px;
  }
}

.text-danger {
  color: #f56c6c;
  font-weight: 600;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>